﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Networking;

namespace CJ.XNFZ.Server {
    public class XNFZServerHelper : Singleton<XNFZServerHelper> {

        public XNFZServerConfig config;

        public string file = "path.json";

        public string username;
        public string nickname;
        public string token;

        public void GetConfig (Action ok = null, Action<string> error = null) {
            XNFZTemplateHelper.Instance.GetConfig (
                file,
                (string json) => {
                    config = JsonUtility.FromJson<XNFZServerConfig> (json);
                    if (ok != null) ok ();
                },
                (string e) => {
                    if (error != null) error ("获取配置文件错误");
                }
            );
        }

        public void GoAdmin () {

            Application.OpenURL (config.adminURL);
        }

        public void Login (string username, string password, Action ok = null, Action<string> error = null) {
            StartCoroutine (_Login (username, password, ok, error));
        }

        public void Regist (string username, string password, Action ok = null, Action<string> error = null) {
            if (string.IsNullOrEmpty (username) || string.IsNullOrEmpty (password)) {
                if (error != null) error ("用户名或密码为空");
                return;
            }
            if (!CheckIDString (username)) {
                if (error != null) error ("用户名格式错误");
                return;
            }
            if (!CheckPassString (password)) {
                if (error != null) error ("密码格式错误");
                return;
            }
            StartCoroutine (_Regist (username, password, ok, error));
        }

        public void Log (string packageid, string version, List<string> keys, List<string> scores, List<string> startTime, List<string> endTime, List<string> repeatCount, long now, Action ok = null, Action<string> error = null) {
            //StartCoroutine (_Log (username, packageid, version, keys, scores, startTime, endTime, repeatCount, now, ok, error));
        }

        IEnumerator _Login (string username, string password, Action ok = null, Action<string> error = null) {
            LoginReq body = new LoginReq ();
            body.username = username;
            body.password = password;
            byte[] postData = System.Text.Encoding.UTF8.GetBytes (JsonUtility.ToJson (body));
            var req = new UnityWebRequest (config.loginURL, "POST");
            req.uploadHandler = (UploadHandler) new UploadHandlerRaw (postData);
            req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer ();
            req.SetRequestHeader ("Content-Type", "application/json; charset=utf-8");
            yield return req.SendWebRequest ();

            if (req.isNetworkError || req.isHttpError) {
                Debug.LogError ("login error：" + req.responseCode + " " + JsonUtility.ToJson (body) + " " + req.downloadHandler.text);
                //登录失败
                if (req.downloadHandler.text.Contains ("incorrect")) {
                    if (error != null) error ("用户名或密码错误");
                } else {
                    if (error != null) error (req.error);
                }
            } else {
                var res = JsonUtility.FromJson<LoginRes> (req.downloadHandler.text);
                this.username = username;
                this.nickname = username;
                this.token = res.token;
                XNFZTemplateHelper.Instance.ShowName ("用户：" + this.nickname);
                if (ok != null) ok ();
            }
        }

        IEnumerator _Regist (string username, string password, Action ok = null, Action<string> error = null) {
            RegistReq body = new RegistReq ();
            body.username = username;
            body.password = password;
            body.name = username;
            byte[] postData = System.Text.Encoding.UTF8.GetBytes (JsonUtility.ToJson (body));
            var req = new UnityWebRequest (config.registerURL, "POST");
            req.uploadHandler = (UploadHandler) new UploadHandlerRaw (postData);
            req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer ();
            req.SetRequestHeader ("Content-Type", "application/json; charset=utf-8");
            yield return req.SendWebRequest ();

            if (req.isNetworkError || req.isHttpError) {
                Debug.LogError ("login error：" + req.responseCode + " " + req.downloadHandler.text);
                //注册失败，飘字
                if (req.downloadHandler.text.Contains ("already")) {
                    if (error != null) error ("用户已存在");
                } else {
                    if (error != null) error ("注册失败");
                }
            } else {
                if (ok != null) ok ();
            }
        }

        IEnumerator _Log (string username, string packageid, string version, List<string> keys, List<string> scores, List<string> startTime, List<string> endTime, List<string> repeatCount, long now, Action ok = null, Action<string> error = null) {
            if (keys == null) {
                if (error != null) error ("无效参数");
                Debug.Log("1");
                yield break;;
            }
            if (scores == null) {
                if (error != null) error ("无效参数");
                Debug.Log("2");
                yield break;;
            }
            if (startTime == null)
            {
                if (error != null) error("无效参数");
                Debug.Log("3");
                yield break; ;
            }
            if (endTime == null)
            {
                if (error != null) error("无效参数");
                Debug.Log("4");
                yield break; ;
            }
            if (repeatCount == null)
            {
                if (error != null) error("无效参数");
                Debug.Log("5");
                yield break; ;
            }
            if (keys.Count != scores.Count
                || keys.Count != startTime.Count
                || keys.Count != endTime.Count
                || keys.Count != repeatCount.Count) {
                if (error != null) error ("无效参数");
                Debug.Log("6");

                yield break;;
            }
            UploadlogReq body = new UploadlogReq ();
            body.user = username;
            body.package = packageid;
            body.version = version;
            body.data = new List<ScoreKeyValue> ();
            for (int i = 0; i < keys.Count; i++) {
                var item = new ScoreKeyValue ();
//                item.key = keys[i];
                item.score = scores[i];
                item.startTime = startTime[i];
                item.endTime = endTime[i];
                item.repeatCount = repeatCount[i];
                body.data.Add (item);
            }
            body.time = now;
            Debug.Log(JsonUtility.ToJson (body));
            byte[] postData = System.Text.Encoding.UTF8.GetBytes (JsonUtility.ToJson (body));
            var req = new UnityWebRequest (config.logURL, "POST");
            req.uploadHandler = (UploadHandler) new UploadHandlerRaw (postData);
            req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer ();
            req.SetRequestHeader ("Content-Type", "application/json; charset=utf-8");
            req.SetRequestHeader("Authorization", "Bearer " + this.token);
            yield return req.SendWebRequest ();

            if (req.isNetworkError || req.isHttpError) {
                Debug.LogError ("login error：" + req.responseCode + " " + req.downloadHandler.text);
                if (error != null) error ("上传失败");
            } else {
                if (ok != null) ok ();
            }
        }

        bool CheckIDString (string id) {
            Regex rex = new Regex ("^[a-z0-9A-Z]{2,14}$");
            var idResult = rex.Match (id);
            if (idResult.Success) {
                return true;
            }
            return false;
        }

        bool CheckPassString (string pass) {
            Regex rex = new Regex ("^.{3,20}$");
            var passResult = rex.Match (pass);
            if (passResult.Success) {
                return true;
            }
            return false;
        }

    }
}